#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define N 128

int main(int argc,char const *argv[])
{
    //终端传参数是否符合要求
    if(argc < 3)
    {
        //参数个数不符合，输出错误
        fprintf(stderr,"Uasge:%s ip port\n",argv[0]);
        exit(-1);
    }

    //第一步：创建套接字
    int my_sock;
    if((my_sock = socket(AF_INET,SOCK_DGRAM,0)) == -1)
    {
        perror("fail to socket");
        exit(-1);
    }

    //第二步：初始化ip地址结构体
    struct sockaddr_in server_addr;
    socklen_t addrlen = sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    //第三步：将网络信息结构体与套接字绑定
    if(bind(my_sock,(struct sockaddr *)&server_addr,addrlen) == -1)
    {
        perror("fail to bind");
        exit(-1);
    }
    
    //第四步：接收客户端数据,发送处理数据
    char buf_recv[N] = "";
    char *buf_send;
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    int count = 1;
    while(1)
    {
        memset(buf_recv,0,N);
        //接收客户端数据
        if(recvfrom(my_sock,buf_recv,N,0,(struct sockaddr*)&client_addr,&client_len) == -1)
        {
            perror("fail to recvfrom");
            exit(-1);
        }
        if(count != 0)
        {
            count = 0;
            printf("ip:[%s],port[%d]\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
        }
        printf("from client: %s\n",buf_recv);
        //发送处理数据
        buf_send = strcat(buf_recv,"[yes]");
        if(sendto(my_sock,buf_send,N,0,(struct sockaddr *)&client_addr,addrlen) == -1)
        {
            perror("fail to sendto");
            exit(-1);
        }
    }

    return 0;
}